package com.my.screenadapter.net.myConvert;

import android.util.Log;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by zhangyingjie on 2019-10-29
 *
 * @function only 修改此  convert 方法
 *
 * {@link com.my.screenadapter.net.retrofit.RetrofitActivity#myConvertFacory(View)}
 */
public class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    MyGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        // 在这里通过 value 拿到 json 字符串进行解析
        // 判断状态码是失败的情况，就抛出异常
        String string = value.string();
        try {
            JSONObject object = new JSONObject(string);
            if (object.has("data")){
                String data = object.getString("data");
                if ("".equals(data)||"[]".equals(data)){
//                    Log.i(this.getClass().getSimpleName(), "convert:data-----> "+data);
                    object.put("data",null);
                }
            }
            return adapter.fromJson(object.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
//        JsonReader jsonReader = gson.newJsonReader(value.charStream());
//        try {
//            return adapter.read(jsonReader);
//        } finally {
//            value.close();
//        }
    }
}
